﻿using System;
using System.Collections.Generic;
using System.IO;
using CSJ2K.Util.IO;

namespace CSJ2K.Jpc.Segments
{
    /// <summary>Component registration (CRG)</summary>
    /// <comment>
    /// Function: Allows specific registration of components with respect to each other. For 
    ///      coding purposes the samples of components are considered to be located at 
    ///      reference grid points that are integer multiples of XRsiz and YRsiz (see A.5.1). 
    ///      However, this may be inappropriate for rendering the image. The CRG marker segment
    ///      describes the "centre of mass" of each component's samples with respect to the 
    ///      separation. This marker segment has no effect on decoding the codestream. 
    /// Usage: Main header only. Only one CRG may be used in the main header and is applicable 
    ///      for all tiles. 
    /// Length: Variable depending on the number of components.
    /// </comment>
    public class CRG : Segment
    {
        public struct ComponentInfo
        {
            public ushort X; // Value of the horizontal offet, in units of 1/65536 of the horizontal separation XRsiz for the ith component.
            public ushort Y; // Value of the vertical offert, in units of 1/65536 of the vertical separation YRsiz, for the ith component.
        }
        public ComponentInfo[] Component;

        public CRG(Stream source)
            : this(source, (Markers)StreamUtil.ReadBUInt16(source)) { }
        public CRG(Stream source, Markers marker)
            : base(source, marker, true)
        {
            if (marker != Markers.CRG) throw (new ApplicationException("Attempting to create segment of the wrong type."));

            Component = new ComponentInfo[(Length - 2) / 4];
            for(int i=0; i<Component.Length; i++)
            {
                Component[i]=new ComponentInfo();
                Component[i].X = StreamUtil.ReadBUInt16(source);
                Component[i].Y = StreamUtil.ReadBUInt16(source);
            }
        }
    }
}
